import 'dart:async';
import 'dart:convert';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:exread/Books.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;

class ScanQRCode extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new ScanState();
  }

}

class ScanState extends State<ScanQRCode> {
  String barcode = "";
  Book book = new Book("", "", "", "", "");

  @override
  Widget build(BuildContext context) {
    IconData iconData = Icons.check_circle_outline;
    Color color = Colors.white;
    if (book.isbn.isEmpty) {
      color = Colors.grey;
    }

    return new Scaffold(
      appBar: new AppBar(
        title: new Text("添加新书"),
        actions: <Widget>[new IconButton(
            icon: new Icon(iconData, color: color,),
            onPressed: () => _postData(book)),
        ],
      ),
      backgroundColor: Colors.lightBlue,

      body: new Center(
          child: new Container(
              margin: const EdgeInsets.symmetric(
                  horizontal: 10.0, vertical: 25.0),
              padding: const EdgeInsets.symmetric(
                  horizontal: 15.0, vertical: 25.0),
              decoration: new BoxDecoration(
                color: Colors.grey.shade200.withOpacity(0.2),
                borderRadius: new BorderRadius.circular(5.0),
              ),
              child: showContent(context))),
      floatingActionButton: new FloatingActionButton(
        onPressed: scan,
        tooltip: '扫码添加',
        child: new Icon(Icons.add_a_photo),
      ),
    );
  }

  Widget showContent(BuildContext context) {
    if (book.isbn.isNotEmpty) {
      return showBook(context);
    } else {
      return showInput(context);
    }
  }

  Widget showBook(BuildContext context) {
    final TextStyle nameStyle = new TextStyle(
        fontSize: 18.0, color: Colors.black54);
    final TextStyle authorStyle = new TextStyle(
        fontSize: 15.0, color: Colors.blueGrey);
    return new Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        new Image.network(book.coverImage, width: 180.0, height: 200.0,),
        new Padding(
          padding: new EdgeInsets.only(top: 10.0),
          child: new Text(book.bookName, style: nameStyle),
        ),
        new Text(book.author, style: authorStyle,),
      ],
    );
  }

  Widget showInput(BuildContext context) {
    return new TextField(
      decoration: new InputDecoration(labelText: '请输入图书ISBN'),
      onSubmitted: (String str) => _loadData(str),
    );
  }

  Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      print(barcode);
      _loadData(barcode);

      setState(() => this.barcode = barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          this.barcode = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() => this.barcode = 'Unknown error: $e');
      }
    } on FormatException {
      setState(() =>
      this.barcode =
      'null (User returned using the "back"-button before scanning anything. Result)');
    } catch (e) {
      setState(() => this.barcode = 'Unknown error: $e');
    }
  }

  //http 加载数据
  void _loadData(String isbn) async {
    String dataUrl = "https://api.douban.com/v2/book/isbn/" + isbn;

    try {
      http.Response response = await http.get(dataUrl);
      print("${response.body}");

      setState(() {
        book = Book.fromDuoban(json.decode(response.body));
      });
    } on Exception catch (e) {
      print("exception $e");
      SnackBar mSnackBar = new SnackBar(content: new Text("加载数据错误"));
      Scaffold.of(context).showSnackBar(mSnackBar);
    }
  }

  //添加一本新书
  void _postData(Book book) async {
    if (book != null && book.isbn.isNotEmpty) {
      String dataUrl = "https://api.bmob.cn/1/classes/book/";

      //设置请求头
      Map<String, String> map = new Map();
      map["Content-Type"] = "application/json";
      map["X-Bmob-Application-Id"] = "ce30565639d0fb10cd925b5b024c3408";
      map["X-Bmob-REST-API-Key"] = "4057ff07b1bec5590fb4ff0a16141938";
      try {
        http.Response response = await http.post(
            dataUrl, headers: map, body: json.encode(book));
        print("${response.body}");
      } on Exception catch (e) {
        print("exception $e");
        SnackBar mSnackBar = new SnackBar(content: new Text("上传数据错误"));
        Scaffold.of(context).showSnackBar(mSnackBar);
      }

      //关闭页面，没设置返回值 book.isbn
      Navigator.pop(context,book.isbn);
    }
  }

}